package com.container.core;

import javax.servlet.*;
import java.io.IOException;
import java.util.Iterator;

import static com.google.common.base.Preconditions.checkNotNull;

public class MyFilterChain implements FilterChain {
    private final Iterator<Filter> itr;
    private final Servlet servlet;

    public MyFilterChain(Servlet servlet, Iterable<Filter> filters) throws ServletException {
        this.itr = checkNotNull(filters).iterator();
        this.servlet = checkNotNull(servlet);
    }

    //每个Filter在处理完请求之后调用该方法。如果有下一个Filter，调用其doFilter()方法；如果没有，则调用servlet的service()方法。
    @Override
    public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
        if (itr.hasNext()) {
            Filter filter = itr.next();
            filter.doFilter(request, response, this);
        } else {
            servlet.service(request, response);
        }
    }
}
